package com.pisolution.actuator.service.schedule;

import com.pisolution.actuator.service.constant.ServiceInstantStatus;
import com.pisolution.actuator.service.mapper.PiActuatorServiceInstanceMapper;
import com.pisolution.actuator.service.model.PiActuatorServiceInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Instant;
import java.util.concurrent.*;

/**
 * @author likai
 * @version 1.0.0
 * @ClassName HeartbeatMonitor.java
 * @Description TODO
 * @createTime 2021年09月02日 15:30:00
 */
public class HeartbeatMonitor implements Runnable{

    private final static Logger log = LoggerFactory.getLogger(HeartbeatMonitor.class);

    private ScheduledExecutorService scheduledExecutorService;

    private volatile ScheduledFuture<?> scheduledFuture;

    //数据库操作句柄
    private PiActuatorServiceInstanceMapper piActuatorServiceInstanceMapper;

    //实例id
    private String instanceId;

    //实例状态
    private String status;

    @Override
    public void run() {
        log.info("心跳丢失：{}", instanceId);
        PiActuatorServiceInstance instance = new PiActuatorServiceInstance();
        instance.setId(Long.valueOf(instanceId));
        instance.setInstanceStatus(ServiceInstantStatus.DOWN.getCode());
        instance.setUpdateTime(Instant.now());
        piActuatorServiceInstanceMapper.updateById(instance);
    }

    //无参构造
    HeartbeatMonitor(){ }

    //有参构造
    public HeartbeatMonitor(ScheduledExecutorService scheduledExecutorService, PiActuatorServiceInstanceMapper piActuatorServiceInstanceMapper, String instanceId, String sstatus){
        this.piActuatorServiceInstanceMapper = piActuatorServiceInstanceMapper;
        this.instanceId = instanceId;
        this.scheduledExecutorService = scheduledExecutorService;
        this.status = sstatus;
    }

    /**
     * @title 重置时间线
     * @description
     * @author admin
     * @updateTime 2021/9/2 15:55
     * @throws
     */
    public void resetHeartbeat(long delaySeconds){
        if(this.scheduledFuture != null && !this.scheduledFuture.isCancelled()){
            this.scheduledFuture.cancel(true);
        }
        this.scheduledFuture = scheduledExecutorService.schedule(this, delaySeconds, TimeUnit.SECONDS);
    }

    /**
     * @title
     * @description
     * @author admin
     * @updateTime 2021/9/3 10:23
     * @throws
     */
    public void cancel(){
        if(this.scheduledFuture != null && !this.scheduledFuture.isCancelled()){
            this.scheduledFuture.cancel(true);
        }
    }
}
